using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using FreeLancer.HRB.Services;
using FreeLancer.HRB.Domains;
using FreeLancer.HRB.Core.Services;
using DevExpress.Web.ASPxClasses;
using System.Xml;
using DevExpress.Web.ASPxUploadControl;

namespace FreeLancer.HRB.WebApp.Admin.Pages
{
  public partial class Ads : System.Web.UI.Page
  {
    #region Private Members

    private AdvsService _advService = new AdvsService();
    private TList<Advs> _advs = new TList<Advs>();

    private const string Delete = "Delete";
    private const string Add = "Add";
    private const string Update = "Update";
    private const string Load = "Load";
    private const string AdsImagePath = "~/Images/AdImages/";

    #endregion

    #region Page Events

    protected void Page_Init(object sender, EventArgs e)
    {
      LoadLanguage();
      InitializeData();
    }

    protected void Page_Load(object sender, EventArgs e)
    {
      lblErrorUpdateFailed.Visible = false;
      lblErrorLoadFailed.Visible = false;
      lblErrorDeleteFailed.Visible = false;
    }

    #endregion

    #region cboLanguage Events

    protected void cboLanguage_SelectedIndexChanged(object sender, EventArgs e)
    {
    }

    #endregion

    #region Upload

    protected void ASPxUploadControl_FileUploadComplete(object sender, FileUploadCompleteEventArgs e)
    {
      if (e.IsValid)
      {
        string path = Server.MapPath(AdsImagePath);
        DateTime now = DateTime.Now;
        path = path + now.ToString("yyyy_MM_dd_hh_mm_ss") + "_" + ASPxUploadControl.FileName;
        e.CallbackData = now.ToString("yyyy_MM_dd_hh_mm_ss") + "_" + ASPxUploadControl.FileName;

        ASPxUploadControl.SaveAs(path, true);
      }
    }

    #endregion

    #region Dataview

    protected void ASPxDataView_OnCustomCallback(object sender, CallbackEventArgsBase e)
    {
      ExecuteCommand(e.Parameter);
    }

    #endregion

    #region Load Image Information

    protected void ASPxCallbackPanel_OnCallback(object sender, CallbackEventArgsBase e)
    {
      ExecuteCommand(e.Parameter);
    }

    #endregion

    #region Save Image by Post back

    protected void ASPxButtonUpdate_OnClick(object sender, EventArgs e)
    {
      if (_advs.Count > 0)
      {
        ASPxDataView.DataSource = _advs;
        ASPxDataView.DataBind();
        return;
      }

      bool flagSuccess = false;
      Advs ad = new Advs();
      
      try
      {
        using (ConnectionScope.CreateTransaction())
        {
          if (ad != null)
          {
            ad.Tooltip = ASPxTextBoxImageTitle.Text;
            //ad.Description = ASPxMemoImageDescription.Text;
            ad.LinkPage = ASPxTextBoxImageLink.Text.Replace('[', ':');
            ad.Index = (string.IsNullOrEmpty(ASPxTextBoxIndex.Text) == true) ? null : (int?)int.Parse(ASPxTextBoxIndex.Text);

            if (!string.IsNullOrEmpty(ASPxTextBoxImageName.Text))
              ad.Path = ASPxTextBoxImageName.Text;

            _advService.Save(ad);
          }

          flagSuccess = ConnectionScope.Complete();
          if (flagSuccess)
          {
            _advs.Add(ad);
            ASPxDataView.DataSource = _advs;
            ASPxDataView.DataBind();
          }
        }
      }
      catch (Exception ex)
      {
        LoggingService.LogCritical("Admin-Ads Page", "Can not add Ad.", ex,
              LoggingService.DefaultCategory, true);
      }
    }

    #endregion

    #region Page Processing

    /// <summary>
    /// Initialize language to combobox
    /// </summary>
    private void LoadLanguage()
    {
      //int total = 0;
      //LanguagesService languageService = new LanguagesService();
      //TList<Languages> languages = languageService.GetPaged("IsActive='True'", string.Empty, 0, 3, out total);
      //cboLanguage.DataSource = languages;
      //cboLanguage.DataTextField = "Name";
      //cboLanguage.DataValueField = "LanguageID";
      //cboLanguage.DataBind();
    }

    private void LoadAds()
    {
      try
      {
        _advs = _advService.GetAll();
      }
      catch (Exception e)
      {
        LoggingService.LogCritical("Admin-Ads Page", "Can not load data for Ad",
          e, LoggingService.DefaultCategory, true);
      }

      if (_advs.Count > 0)
        ASPxButtonUpdate.AutoPostBack = false;
      else
        ASPxButtonUpdate.AutoPostBack = true;

      ASPxDataView.DataSource = _advs;
      ASPxDataView.DataBind();
    }

    /// <summary>
    /// Initialize for GridView Post
    /// </summary>
    private void InitializeData()
    {
      try
      {
        LoadAds();
      }
      catch (Exception ex)
      {
        LoggingService.LogCritical("Admin-Ads Page", "Exception when get Ads",
          ex, LoggingService.DefaultCategory, true);
      }
    }

    #endregion

    #region Image Processing Commands

    private void ExecuteCommand(string parameter)
    {
      string[] parameters = parameter.Split(new char[] { '|' }, StringSplitOptions.RemoveEmptyEntries);

      bool flagSuccess = false;

      if (parameters.Length > 1)
      {
        switch (parameters[1])
        {
          case Load:
            flagSuccess = LoadImage(parameters[0]);
            break;
          case Add:
            flagSuccess = AddImage(parameters);
            break;
          case Update:
            flagSuccess = UpdateImage(parameters);
            break;
          case Delete:
            flagSuccess = DeleteImage(parameters[0]);
            break;
        }
      }

      if (flagSuccess)
      {
        ASPxDataView.DataSource = _advs;
        ASPxDataView.DataBind();
      }
    }

    private bool DeleteImage(string adId)
    {
      bool flagSuccess = false;
      Advs ad = _advs.Find(AdvsColumn.AdvId, int.Parse(adId));
      try
      {
        using (ConnectionScope.CreateTransaction())
        {
          if (ad != null)
          {
            _advs.Remove(ad);
            if (ad.AdvId > 0)
              _advService.Delete(ad);
          }
          else
          {
            if (int.Parse(adId) > 0)
              _advService.Delete(int.Parse(adId));
          }

          flagSuccess = ConnectionScope.Complete();
        }
      }
      catch (Exception ex)
      {
        LoggingService.LogCritical("Admin-Edit Event Page", "Can not delete Image.", ex,
              LoggingService.DefaultCategory, true);
      }
      return flagSuccess;
    }

    private bool UpdateImage(string[] parameters)
    {
      bool flagSuccess = false;
      Advs ad = _advs.Find(AdvsColumn.AdvId, int.Parse(parameters[0]));

      XmlDocument doc = new XmlDocument();
      doc.LoadXml(parameters[2]);
      XmlElement root = doc.DocumentElement;

      try
      {
        using (ConnectionScope.CreateTransaction())
        {
          if (ad != null)
          {
            ad.Tooltip = root.ChildNodes[0].Attributes["Text"].Value;
            //ad.Description = root.ChildNodes[1].Attributes["Text"].Value;
            ad.LinkPage = root.ChildNodes[1].Attributes["Text"].Value.Replace('[', ':');
            if (!string.IsNullOrEmpty(root.ChildNodes[2].Attributes["Text"].Value))
              ad.Path = root.ChildNodes[2].Attributes["Text"].Value;
            ad.Index = (string.IsNullOrEmpty(root.ChildNodes[3].Attributes["Text"].Value) == true) ?
              null : (int?)int.Parse(root.ChildNodes[3].Attributes["Text"].Value);

            _advService.Save(ad);
          }

          flagSuccess = ConnectionScope.Complete();
        }
      }
      catch (Exception ex)
      {
        LoggingService.LogCritical("Admin-Edit Event Page", "Can not update Image.", ex,
              LoggingService.DefaultCategory, true);
      }
      return flagSuccess;
    }

    private bool AddImage(string[] parameters)
    {
      bool flagSuccess = false;
      Advs ad = new Advs();

      XmlDocument doc = new XmlDocument();
      doc.LoadXml(parameters[2]);
      XmlElement root = doc.DocumentElement;

      try
      {
        using (ConnectionScope.CreateTransaction())
        {
          if (ad != null)
          {
            ad.Tooltip = root.ChildNodes[0].Attributes["Text"].Value;
            //image.Description = root.ChildNodes[1].Attributes["Text"].Value;
            ad.LinkPage = root.ChildNodes[1].Attributes["Text"].Value.Replace('[', ':');
            if (!string.IsNullOrEmpty(root.ChildNodes[2].Attributes["Text"].Value))
              ad.Path = root.ChildNodes[2].Attributes["Text"].Value;
            ad.Index = (string.IsNullOrEmpty(root.ChildNodes[3].Attributes["Text"].Value) == true) ?
              null : (int?)int.Parse(root.ChildNodes[3].Attributes["Text"].Value);

            _advService.Save(ad);
          }

          flagSuccess = ConnectionScope.Complete();
          if (flagSuccess)
            _advs.Add(ad);
        }
      }
      catch (Exception ex)
      {
        LoggingService.LogCritical("Admin-Edit Event Page", "Can not add Image.", ex,
              LoggingService.DefaultCategory, true);
      }
      return flagSuccess;
    }

    private bool LoadImage(string adId)
    {
      bool flagSuccess = false;
      Advs ad = _advs.Find(AdvsColumn.AdvId, int.Parse(adId));

      if (ad != null)
      {
        //ASPxMemoImageDescription.Text = image.Description;
        ASPxTextBoxImageLink.Text = ad.LinkPage;
        ASPxTextBoxImageTitle.Text = ad.Tooltip;
        ASPxImage.ImageUrl = AdsImagePath + ad.Path;
        ASPxTextBoxIndex.Text = (ad.Index.HasValue == true) ? 
          ad.Index.ToString() : string.Empty;

        flagSuccess = true;
      }

      return flagSuccess;
    }

    #endregion
  }
}
